<template>
    <el-card>
        <ResidentSearch @findResidentsData="findResidentsData"
        v-model:selectData="selectData"/>

        <!-- 表格 -->
        <el-table :data="residentsData.rows" stripe style="width: 100%;font-size: 13px;"
            :header-cell-style="{ background: '#f2f2f2', fontWeight: 'normal', 
            color: '#515a6e', height: '54px' ,textAlign: 'center'}"
            :cell-style="{ height: '54px' ,textAlign: 'center'}">
            <el-table-column type="selection" />
            <el-table-column prop="_id" label="编号" width="120px"/>
            <el-table-column label="姓名" width="130px">
                <template #default="scope">
                   <div class="flex-bc">
                     <el-avatar :src="scope.row.avatar" :size="40"></el-avatar>
                    {{ scope.row.name }}
                   </div>
                </template>
            </el-table-column>
            <el-table-column prop="IDnumber" label="身份证号" />
            <el-table-column prop="phone" label="手机号码" />
            <el-table-column label="签约状态">
              <template #default="scope">
                <template v-if="scope.row.state=='0'"><span style="color: #FDDB78;">待签约</span></template>
                <template v-else-if="scope.row.state==1"><span style="color: #3DD4A7;">签约中</span></template>
                <template v-else-if="scope.row.state==2"><span style="color: #3DD4A7;">已签约</span></template>
                <template v-else><span style="color: #FA746B;">待续约</span></template>
              </template>
            </el-table-column>
            <el-table-column prop="tagIds" label="用户标签" width="185px">
                <template #default="scope">
                    <el-space>
                        <el-tag v-for="item in scope.row.tagIds" :key="item._id" round :type="tagColor[item.name]"> 
                        {{ item.name }}
                    </el-tag>
                    </el-space>
                </template>
            </el-table-column>
            <el-table-column label="居民状态" width="80px">
                <template #default="{ row }">
                    <el-switch disabled v-model="rstate" :active-value="0" :inactive-value="1" active-text="启用"
                        inactive-text="禁用" inline-prompt style="--el-switch-on-color:#13ce66" @change="onUpdateResident(row)"/>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="276">
                <template #default="{ row }">
                    <el-button class="table-button" type="primary" v-permission="'居民详情'" link @click="pageToInfo(row._id)">查看详情</el-button>
                    <el-button class="table-button" type="primary" link @click="pageToUpdate(row._id)">编辑</el-button>
                    <el-button class="table-button" type="primary" link>发消息</el-button>
                    <el-button class="table-button" type="primary" link>添加服务</el-button>
                    <el-button class="table-button" type="danger" link @click="onDeleteResident(row._id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="flex-end" style="margin-top: 22px;">
            <el-pagination v-model:current-page="pageData.currentPage" v-model:page-size="pageData.pageSize"
            :page-sizes="[5, 10, 20, 40]" background
            layout="total, sizes, prev, pager, next, jumper" :total="residentsData.total" />
        </div>
    </el-card>
</template>

<script setup>

import { onMounted, reactive, ref, watch } from 'vue';
import { deleteResidentsApi, findResidentsApi, updateResidentsApi } from '../../api/residents';
import { useRouter } from 'vue-router'
import ResidentSearch from './search/ResidentSearch.vue';
import { useFindData } from '../../composables/findData';
const router = useRouter();
const rstate = ref(0)
// const residentsData = reactive({
//     rows: [], total: 0
// })
const residentsData = ref({
    rows: [], total: 0
})
// 机构数据、团队数据
const { AgencyData,findAgencyAsync,TeamData,findTeamAsync } = useFindData()


const selectData = ref({
    input_search: '',
    state: '',
    organizationId: '',
    teamId: '',
    servicePackId: '',
    tagIds: ''
});

const tagColor = {'高血压':'danger','冠心病':'warning','高血糖':'success','低血糖':'success'}
const pageData = ref({
    currentPage:1,
    pageSize:10
})

onMounted(() => {
    findResidentsData();
})

watch(pageData.value, () => {
    findResidentsData();    
})

// watch(residentsData)
function fuzzySearch(text, search) {
  // 将搜索词转换为 "a.*b.*c" 形式
  const pattern = search.split('').join('.*');
  const regex = new RegExp(pattern, 'i');
  return regex.test(text);
}

// 查询居民
function findResidentsData() {
    if(Boolean(selectData.value.input_search)){
        residentsData.value.rows = residentsData.value.rows.filter(item=>{
            return (fuzzySearch(item.name,selectData.value.input_search))
        })
    }else{
    findResidentsApi({
        ...pageData.value,
        ...selectData.value
    }).then(res => {
        console.log(res);
        
       if(res.code==200){
         residentsData.value.rows = res.data.rows;
        residentsData.value.total = res.data.total;
        // todo
        console.log(residentsData.value,'居民数据');
       }
    })
    }
    
}

// 删除居民
function onDeleteResident(_id) {
    ElMessageBox.confirm(
        '居民信息删除后无法恢复,确认要删除吗?',
        '删除确认',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            deleteResidentsApi({ _id })
                .then(res => {
                    // todo  delete
                    console.log(res);
                    if (res.code == 200) {
                        ElMessage.success('删除成功');
                        findResidentsData();
                    }
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除失败',
            })
        })
}
// end删除居民

// 修改居民状态
function onUpdateResident(data){ 
    updateResidentsApi({
        _id:data._id,
        rstate:data.rstate
    })
}
// end修改居民状态


// 跳转编辑页面
function pageToUpdate(_id){
    router.push({ path:'/resident/update/:_id',query:{_id}})
}
// end跳转编辑页面
// 跳转详情页面
function pageToInfo(_id){
    router.push({ path:'/resident/detail/:_id',query:{_id}})
}


</script>

<style scoped lang="scss">
.table-button {
    font-size: 13px;
    font-weight: 400;
    margin-left: 0;
}
</style>